import type { DeptTypeEntityReq } from "@/api/types";
import type { UseBaseForm } from "@/composables";
import { ElMessage } from "element-plus";
import { deptTypeApi } from "@/api";
import { useBaseForm } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";
import { onlySubmitData } from "@/utils/tools";

interface UseDeptTypeForm extends UseBaseForm<DeptTypeEntityReq> {
    handleSubmit: (isEdit: boolean, callback?: () => void) => Promise<void>;
}

export function useDeptTypeForm(): UseDeptTypeForm {
    /** 获取重置表单数据 */
    const getInitFormData = (): DeptTypeEntityReq => ({
        id: undefined,
        name: "",
        icon: null,
        remark: null,
        cascadeLevel: [],
    });

    const { formRef, submitLoading, formData, resetForm } = useBaseForm(getInitFormData);

    /** 提交表单 */
    async function handleSubmit(isEdit: boolean, callback?: () => void): Promise<void> {
        if (!(await formRef.value?.validate())) return;
        submitLoading.value = true;

        const submitData = onlySubmitData(getInitFormData(), formData);
        const apiFn = isEdit ? deptTypeApi.update : deptTypeApi.create;

        apiCall(
            () => apiFn(submitData),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                callback?.();
            },
            {
                onFinally: () => {
                    submitLoading.value = false;
                },
            },
        );
    }

    return {
        formData,
        formRef,
        submitLoading,
        resetForm,
        handleSubmit,
    };
}
